package com.fivestar.pmanager.web.auth;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;
import java.util.Iterator;

public class MyAccessDecisionManager implements AccessDecisionManager
{
    private static final Logger logger = LoggerFactory.getLogger(MyAccessDecisionManager.class);


    @Override
    public void decide(Authentication authentication, Object o,
            Collection<ConfigAttribute> collection)
            throws AccessDeniedException, InsufficientAuthenticationException
    {
        if(collection == null || collection.isEmpty())
        {
            throw new AccessDeniedException(" 没有权限访问！ ");
        }
        //所请求的资源拥有的权限(一个资源对多个权限)
        Iterator<ConfigAttribute> iterator = collection.iterator();
        while(iterator.hasNext())
        {
            ConfigAttribute configAttribute = iterator.next();
            //访问所请求资源所需要的权限
            String needRolePermission = configAttribute.getAttribute();
            logger.debug("needPermission is " + needRolePermission);
            //用户所拥有的权限authentication
            for(GrantedAuthority ga : authentication.getAuthorities())
            {
                if(needRolePermission.equals(ga.getAuthority()))
                {
                    return;
                }
            }
        }
        //没有权限
        throw new AccessDeniedException(" 没有权限访问！ ");
    }


    @Override
    public boolean supports(ConfigAttribute configAttribute)
    {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass)
    {
        return true;
    }
}
